//
//  UILabelEx.m
//  ParsingWidget
//
//  Created by Phuong Le on 8/7/13.
//  Copyright (c) 2013 Phuong Le. All rights reserved.
//

#import "UILabelEx.h"
#import "UIConstants.h"

@implementation UILabelEx

- (id)initWithTitle:(NSString*)title titleFont:(UIFont*)titleFont content:(NSString*)content contentFont:(UIFont*)contentFont
{
    self = [super init];
    
    if (self)
    {
        [self setBackgroundColor:[UIColor clearColor]];
        
        //
        _title = [[UILabel alloc] init];
        [_title setText:title];
        [_title setBackgroundColor:[UIColor clearColor]];
        [_title setTextAlignment:NSTextAlignmentLeft];
        [_title setFont:titleFont];
        [self addSubview:_title];
           
        //
        _content = [[UILabel alloc] init];
        [_content setText:content];
        [_content setBackgroundColor:[UIColor clearColor]];
        [_content setTextAlignment:NSTextAlignmentLeft];
        [_content setFont:contentFont];        
        [self addSubview:_content];
        
        _titleWidth = 0;
        _paddingLeftTitle = 0;
        
        _title_h = [@"a" sizeWithFont:_title.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)].height;
        _content_h = [@"a" sizeWithFont:_content.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)].height;
    }
    
    return self;
}

- (NSInteger)calcVisibleHeight
{
    return MAX(_title_h, _content_h);
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    if (_titleWidth > 0)
    {
        [_title setFrame:RECT(_paddingLeftTitle, 0, _titleWidth - _paddingLeftTitle, self.height)];
    }
    else
    {
        CGFloat maxWidthTitle = (2 * self.width) / 5;

        [_title setFrame:RECT(_paddingLeftTitle, 0, maxWidthTitle - _paddingLeftTitle, self.height)];
        
        CGSize expectedTitleSize = [_title.text sizeWithFont:_title.font
                                              constrainedToSize:_title.frame.size
                                                  lineBreakMode:_title.lineBreakMode];
        
        if (expectedTitleSize.width < maxWidthTitle)
        {
            [_title setFrame:RECT(_paddingLeftTitle, 0, expectedTitleSize.width, self.height)];
        }
    }
    
    //
    [_content setFrame:RECT(_title.right+5, 0, self.width - (_title.right+5), self.height)];
}

- (void)dealloc
{
    _title = nil;
    _content = nil;
}

@end
